//axios 插件 基于原生ajax+promise
class Axios {
  constructor() {
    this.xhr = null;
    try {
      this.xhr = new XMLHttpRequest()
    } catch (e) {
      this.xhr = new ActiveXObject("Microsoft.XML")
    }
  }
  // 序列化参数
  serialize (data) {
    //{name:1,age:2}===name=1&age=2
    if (!data) return ''
    var pairs = []
    for (var name in data) {
      if (!data.hasOwnProperty(name)) continue
      if (typeof data[name] === 'function') continue
      var value = data[name].toString()
      name = encodeURIComponent(name)
      value = encodeURIComponent(value)
      pairs.push(name + '=' + value)
    }
    return pairs.join('&')
  }
  // 构造函数的调用方法
  $http ({ method = "get", url = "", data = {}, async = true, header = { 'Content-type': "application/x-www-form-urlencoded" } }) {
    var xhr = this.xhr;
    return new Promise((resolve, reject) => {
      // get 传参
      if (method == "get") {
        url += "?" + this.serialize(data);
      }
      // 2调用open()
      xhr.open(method, url, async)
      // 3调用send()
      if (method == "post") {
        for (let x in header) {
          xhr.setRequestHeader(x, header[x])
        }
        xhr.send(this.serialize(data))
      } else {
        xhr.send()
      }
      // 4.等待数据返回
      xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
          resolve(JSON.parse(xhr.responseText))
        }
        if (xhr.status != 200) {
          var tips = "预期之外的错误"
          if (xhr.status == 404) {
            tips = "请求资源未找到"
          } else if (xhr.status == 400) {
            tips = "客户端请求错误"
          } else if (xhr.status == 500) {
            tips = "服务器端错误"
          }
          reject({ status: xhr.status, tips })
        }
      }
    })
  }
}


export default new Axios();
